﻿using EMS.system.Common;
using EMS.system.Entityies.BaseData;
using EMS.system.Entityies.MasterData.CustomerManagementModel;
using EMS.system.Entityies.MasterData.WorkstationModel;
using EMS.system.IEntityAppService.MasterData.WorkstationService;
using EMS.system.IEntityAppService.MasterData.WorkstationService.WorkstationDTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace EMS.system.EntityAppService.MasterData.WorkstationService
{
    public class WorkstationAppService:ApplicationService,IWorkstationAppService
    {
        private static Object obj = new Object();
        /// <summary>
        /// 工作站仓储
        /// </summary>
        private readonly IRepository<Workstation, int> _workstationRepository;
        /// <summary>
        /// 公共字典类型仓储
        /// </summary>
        private readonly IRepository<DictItem, int> _dictItemRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="workstationRepository"></param>
        public WorkstationAppService(IRepository<Workstation, int> workstationRepository, IRepository<DictItem, int> dictItemRepository)
        {
            _workstationRepository = workstationRepository;
            _dictItemRepository = dictItemRepository;
        }
        /// <summary>
        /// 获取工作站显示 分页 查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="workstationName"></param>
        /// <param name="workshopName"></param>
        /// <returns></returns>
        public async Task< PagedResult> GetWorkstationList(int pageIndex, int pageSize,string? workstationName, string? workshopName)
        {
            var predicate = PredicateBuilder.New<Workstation>(true);
            if (!string.IsNullOrEmpty(workstationName))
            {
                predicate = predicate.And(m => m.WorkstationName .Contains( workstationName));
            }
            if (!string.IsNullOrEmpty(workshopName))
            {
                predicate = predicate.And(m => m.WorkshopName == workshopName);
            }
          
            var dto = await _workstationRepository.GetListAsync(predicate);
            PagedResult result = new PagedResult();
            result.PageCount = (int)Math.Ceiling((decimal)(dto.Count == 0 ? 1 : dto.Count) / pageSize);
            result.PageSize = pageSize;
            result.CurrentPage = pageIndex;
            result.RowCount = dto.Count;
            result.Queryable = dto.Skip((pageIndex - 1) * pageSize).Take(pageSize).AsQueryable();
            return result;
        }
        /// <summary>
        /// 获取字典表数据绑定下拉框
        /// </summary>
        /// <returns></returns>
        public async Task<List<DictItem>>GetDictItems(int dictTypeId)
        {
            var dictItem = await _dictItemRepository.GetListAsync(x=>x.DictTypeId==dictTypeId);
            return dictItem;
        }
        /// <summary>
        /// Redis集群
        /// </summary>
        /// <param name="dictTypeId"></param>
        /// <returns></returns>
        //缓存击穿 （lock锁+2次判断）
        public async Task< List<DictItem>> GetDictItemListRedis(int dictTypeId)
        {
            //根据Key值，获取字典表list集合
            var dictItemList = EMS.system.Common.RedisHelper.Get<List<DictItem>>("DictItemListKey"+ dictTypeId);
            if (dictItemList == null)
            {
                lock (obj)
                {
                    if (dictItemList == null)
                    {
                        //从数据库中取出字典表集合
                        dictItemList = GetDictItems(dictTypeId).Result;
                        var seconds = 30000 + new Random().Next(1, 1000);
                        //将字典表集合缓存在Redis中，key值为：dictItemList
                        EMS.system.Common.RedisHelper.Set("DictItemListKey" + dictTypeId, dictItemList, DateTime.Now.AddDays(1));
                    }
                }
            }
            return dictItemList;
        }


        /// <summary>
        /// 添加工作站
        /// </summary>
        /// <param name="workstationDTO"></param>
        /// <returns></returns>
        public async Task< int> CreateWorkstation(WorkstationDTO workstationDTO)
        {
           
            var workstationName = _workstationRepository.CountAsync(x => x.WorkstationName == workstationDTO.WorkstationName).Result;
            if (workstationName > 0)
            {
                return -1;
            }
            var workstationPlace = _workstationRepository.CountAsync(x => x.WorkstationPlace == workstationDTO.WorkstationPlace).Result;
            if (workstationPlace > 0)
            {
                return -2;
            }
            var workstation = workstationDTO.MapTo< Workstation>();
            await _workstationRepository.InsertAsync(workstation);
            return 1;
        }

        /// <summary>
        /// 删除工作站
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task< int> DeleteWorkstation(string ids)
        {
            string[] arry=ids.Split(',');
            await _workstationRepository.DeleteAsync(x=>ids.Contains(x.Id.ToString()));
            return 1;
        }
        /// <summary>
        /// 获取工作站主键id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<WorkstationDTO> GetWorkstationById(int id)
        {
            var workstation=await _workstationRepository.GetAsync(id);
            var workstationDTO = workstation.MapTo<WorkstationDTO>();
            return workstationDTO;
        }
        /// <summary>
        /// 更新工作站
        /// </summary>
        /// <param name="workstationDTO"></param>
        /// <returns></returns>
        public async Task<int> UpdateWorkstation(WorkstationDTO workstationDTO)
        {
            var workstationCode = _workstationRepository.CountAsync(x => x.WorkstationCode == workstationDTO.WorkstationCode && x.Id != workstationDTO.Id).Result;
            if (workstationCode > 0)
            {
                return -1;
            }
            var workstationName = _workstationRepository.CountAsync(x => x.WorkstationName == workstationDTO.WorkstationName&&x.Id!=workstationDTO.Id).Result;
            if (workstationName > 0)
            {
                return -2;
            }
          
            var workstation = workstationDTO.MapTo<Workstation>();
            await _workstationRepository.UpdateAsync(workstation);
            return 1;
        }
    }
}
